package com.linq.cool.file.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectResult;
import com.linq.cool.file.config.OssProperties;
import com.linq.cool.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: yqlin
 * @Date: 2020/12/30 9:39
 * @Description:
 * @Version: 1.0.0
 */
@Primary
@Service
@Slf4j
public class OssSysFileServiceImpl implements FileService {
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 上传
        // 上传文件所在目录名，当天上传的文件放到当天日期的目录下。19990101/123123.png
        String folderName = DateFormatUtils.format(new Date(), "yyyyMMdd");
        // 保存到 OSS 中的文件名，采用 UUID 命名。
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 从原始文件名中，获取文件扩展名
        String fileExtensionName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        // 文件在 OSS 中存储的完整路径
        String filePath = folderName + "/" + fileName + fileExtensionName;
        OSS ossClient = null;
        try {
            // 获取 OSS 客户端实例
            ossClient = new OSSClientBuilder().build(OssProperties.OSS_END_POINT, OssProperties.OSS_ACCESS_KEY, OssProperties.OSS_SECRET_KEY);

            // 上传文件到OSS 并响应结果
            PutObjectResult putObjectResult = ossClient.putObject(OssProperties.OSS_BUCKET_NAME, filePath, file.getInputStream());
            ResponseMessage response = putObjectResult.getResponse();
            if (response == null) {
                // 上传成功
                // 返回上传文件的访问完整路径
                return OssProperties.OSS_BUCKET_DOMAIN + filePath;
            } else {
                // 上传失败，OOS服务端会响应状态码和错误信息
                String errorMsg = "The error status code for the response:[" + response.getStatusCode() + "]，" +
                        "The error message:[" + response.getErrorResponseAsString() + "]";
                log.error(errorMsg);
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }

    public boolean delete(String fileUrl) {
        // 去除文件 url 中的 Bucket域名 20200729/9d83082760e84c15a685d6e61338174a.png
        String filePath = fileUrl.replace(OssProperties.OSS_BUCKET_DOMAIN, "");
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(OssProperties.OSS_END_POINT, OssProperties.OSS_ACCESS_KEY, OssProperties.OSS_SECRET_KEY);
            // 删除
            ossClient.deleteObject(OssProperties.OSS_BUCKET_NAME, filePath);
            return true;
        } catch (Exception e) {
            log.error("Delete failed：" + e.getMessage());
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
